package org.colafries.metadata.convert.impl;

import com.google.common.base.Strings;
import org.colafries.common.metadata.Column;
import org.colafries.metadata.convert.ITypeConvert;
import org.colafries.metadata.entity.enums.ColumnTypeEnum;
import org.springframework.stereotype.Service;

/**
 * @author Ann
 * @version v1.0
 * @ClassName DamengTypeConvertImpl
 * @Description
 * @date Created in 2024/7/25
 **/
@Service("damengTypeConvertImpl")
public class DamengTypeConvertImpl implements ITypeConvert {
    @Override
    public ColumnTypeEnum convert(Column column) {
        ColumnTypeEnum columnType = ColumnTypeEnum.STRING;
        if (null == column) {
            return columnType;
        }
        Integer length = null == column.getLength() ? 0 : column.getLength();
        String t = Strings.isNullOrEmpty(column.getType()) ? "" : column.getType().toLowerCase();
        boolean isNullable = !column.isKeyFlag() && column.isNullable();
        if (t.contains("numeric") || t.contains("decimal")) {
            columnType = ColumnTypeEnum.DECIMAL;
        } else if (t.contains("bigint")) {
            if (isNullable) {
                columnType = ColumnTypeEnum.JAVA_LANG_LONG;
            } else {
                columnType = ColumnTypeEnum.LONG;
            }
        } else if (t.contains("float")) {
            if (isNullable) {
                columnType = ColumnTypeEnum.JAVA_LANG_FLOAT;
            } else {
                columnType = ColumnTypeEnum.FLOAT;
            }
        } else if (t.contains("double")) {
            if (isNullable) {
                columnType = ColumnTypeEnum.JAVA_LANG_DOUBLE;
            } else {
                columnType = ColumnTypeEnum.DOUBLE;
            }
        } else if (t.contains("boolean") || (t.contains("tinyint") && length.equals(1)) || t.contains("bit")) {
            if (isNullable) {
                columnType = ColumnTypeEnum.JAVA_LANG_BOOLEAN;
            } else {
                columnType = ColumnTypeEnum.BOOLEAN;
            }
        } else if (t.contains("datetime")) {
            columnType = ColumnTypeEnum.TIMESTAMP;
        } else if (t.contains("date")) {
            columnType = ColumnTypeEnum.DATE;
        } else if (t.contains("timestamp")) {
            columnType = ColumnTypeEnum.TIMESTAMP;
        } else if (t.contains("time")) {
            columnType = ColumnTypeEnum.TIME;
        } else if (t.contains("char") || t.contains("text")) {
            columnType = ColumnTypeEnum.STRING;
        } else if (t.contains("binary") || t.contains("blob")) {
            columnType = ColumnTypeEnum.BYTES;
        } else if (t.contains("tinyint") || t.contains("mediumint") || t.contains("smallint") || t.contains("int")) {
            if (isNullable) {
                columnType = ColumnTypeEnum.INTEGER;
            } else {
                columnType = ColumnTypeEnum.INT;
            }
        }
        return columnType;
    }
}
